// pages/morning/morning.js
const util = require('../../utils/util.js');
const app = getApp();
const key = app.globalData.key;
const resurl = app.globalData.resurl;
var missColor = 'rgba(213, 213, 213, 1)';
var ingColor = 'rgba(254, 215, 0, 1)';
var futureColor = 'linear-gradient(0deg,rgba(252,151,98,1),rgba(254,173,99,1))';
let interstitialAd = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDelay: '',
    showGame: true,
    bannerShow: true,
    showFinish: false,
    loginName:'',
    background:'',
    text:'打卡',
    show:false,
    showMask: false,
    wakeNum:'',
    isEarly:'',
    date:'',
    month:'',
    year:'',
    money:app.globalData.money,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this ;
    that.getUserInfo();
    var isDelay = wx.getStorageSync("isDelay");
    that.setData({
      isDelay,
    })
  },
  //获取用户信息接口：
  getUserInfo: function () {
    var that = this;
    that.setData({
      money: app.globalData.money,
    })
    var userId = wx.getStorageSync("userId");
    var _data = {
      deviceProperties: app.globalData.deviceProperties,
      user:{
        userId:userId,
      }
    }
    _data = JSON.stringify(_data);
    _data = util.base64_encode(_data);
    _data = util.xxtea_encrypt(_data, key);
    //获取用户信息接口
    wx.request({
      url:  resurl + '/interface/sdkData?requestId=3&a=1&b=2',
      data:_data,
      header:{
        "content-type":"application/json",
        "dataType":"json",
      },
      method:"post",
      success:function(res){
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        // console.log(res);
        if (res.resultCode === 0) {
          res = JSON.parse(res.data);
          var loginName = unescape(res.user.realName);
          console.log(res);
          that.setData({
            money:res.user.money,
            touxiang:res.user.userLogo,
            loginName:loginName,
          })
        }
      }
          })
  },
  closeGame: function () {
    this.setData({
      showGame: false,
    })
  },
  close:function() {
    var that = this;
    var isDelay = that.data.isDelay;
    if(isDelay == 1) {
      var delayTimer = setInterval(function () {
        that.setData({
          showMiss: false,
          bannerShow: true,
          showFinish: false,
          show:false,
          showMask: false,
        })
        clearInterval(delayTimer);
      },2000)
    } else {
      that.setData({
        showMiss: false,
          bannerShow: true,
          showFinish: false,
          show:false,
          showMask: false,
      })
    }
  },
  finishToast: function () {
    var that = this;
    that.setData({
      showFinish: true,
      showMask: true,
    })
  },
  closeBanner: function () {
    this.setData({
      bannerShow: false,
    })
  },
  back:function (){
    wx.navigateBack({
      delta: 1000
    })
  },

  switch:function() {
    wx.navigateTo({
      url: '/pages/sleep/sleep',
    })
  },
  daka:function () {
    //早晚打卡接口 12
    var that = this;
    var money = that.data.money;
    var userId = wx.getStorageSync("userId");
    var data12 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId:userId,
      }
    }
    data12 = JSON.stringify(data12);
    data12 = util.base64_encode(data12);
    data12 = util.xxtea_encrypt(data12, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=12&a=1&b=2',
      data:data12,
      header:{
        "content-type":"application/json",
        "dataType":"json",
      },
      method:"post",
      success: function(res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if(that.data.isEarly === 1) {
          that.finishToast();
        }
        if(res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          that.finishToast();
          that.setData({
            money: money + res.getMoney,
            background: futureColor,
            text: '打卡成功',
          })
        }
        else if (res.resultCode === -5){
        let now = new Date();
          let timeStamp = now.getTime();
          let beginTime = function (begintime) {
            var bArray = begintime.split(":");
            if(bArray.length !== 2){
              return false;
            }
            var b = new Date();
            b.setHours(bArray[0]);
            b.setMinutes(bArray[1]);
            var btimeStamp = b.getTime();
            return btimeStamp;
          }
          // console.log(beginTime("05:00"));
          let endTime = function (endtime) {
            var eArray = endtime.split(":");
            if(eArray.length !== 2) {
              return false;
            }
            var e = new Date();
            e.setHours(eArray[0]);
            e.setMinutes(eArray[1]);
            var etimeStamp = e.getTime();
            return etimeStamp;
          }
          if(that.data.isEarly === 0){
            if(timeStamp < beginTime("05:00")) {
              that.setData({
                show:true,
                showMask: true,
              })
            } else if (timeStamp > beginTime("09:00")) {
              that.setData({
                show:false,
                showMiss: true,
                showMask: true,
              })
            }
          } 
        }
      }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取早晚打卡页面 接口11
    var that = this;
    that.setData({
      showGame: true,
    })
    var userId = wx.getStorageSync("userId");
    var data11 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId:userId,
      }
    }
    data11 = JSON.stringify(data11);
    data11 = util.base64_encode(data11);
    data11 = util.xxtea_encrypt(data11, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=11&a=1&b=2',
      data:data11,
      header:{
        "content-type":"application/json",
        "dataType":"json",
      },
      method:"post",
      success: function(res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        // console.log('接口11'+res);
        if(res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          let now = new Date();
          let timeStamp = now.getTime();
          let beginTime = function (begintime) {
            var bArray = begintime.split(":");
            if(bArray.length !== 2){
              return false;
            }
            var b = new Date();
            b.setHours(bArray[0]);
            b.setMinutes(bArray[1]);
            var btimeStamp = b.getTime();
            return btimeStamp;
          }
          // console.log(beginTime("05:00"));
          let endTime = function (endtime) {
            var eArray = endtime.split(":");
            if(eArray.length !== 2) {
              return false;
            }
            var e = new Date();
            e.setHours(eArray[0]);
            e.setMinutes(eArray[1]);
            var etimeStamp = e.getTime();
            return etimeStamp;
          }
          if(res.iSearly === 0) {
            if(timeStamp > beginTime("05:00") && timeStamp < endTime("09:00")) {
              that.setData({
                background: ingColor,
                text:'打卡',
              })
            } else if (timeStamp > beginTime("09:00")) {
              that.setData({
                background: missColor,
                text:'已错过',
              })
            } else if (timeStamp < beginTime("05:00")) {
              that.setData({
                background: ingColor,
                text:'打卡',
              })
            }
          } else if ( res.iSearly === 1) {
            that.setData({
              background: futureColor,
              text: '打卡成功',
              show:false,
              showMiss: false,
              showMask: false,
            })
          }
          that.setData({
            wakeNum: res.wakeNum,
            isEarly:res.iSearly,
          })
        }
      }
      })
      var now = new Date();
      var date = now.getDate();
      var month = now.getMonth()+1;
      var year = now.getFullYear();
      if(date < 10) {
        var date = "0"+date;
      }
      if(month < 10) {
        var month = "0"+month;
      }
      that.setData({
        date: date,
        month: month,
        year: year,
      })
      var count = 0;
    var insertScreenAdTimer = setInterval(function () {
      count ++;
      console.log(count);
      if(count > 2) {
        that.insertScreenAD();
        clearInterval(insertScreenAdTimer);
      }
    },1000)
    that.insertScreenAdTimer = insertScreenAdTimer;
  },
  insertScreenAD: function () {
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-1cc4cb154d00aa08'
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(() => { })
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})